import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/article_cart.dart';

import '../../models/article_model.dart';
import '../../services/article_service.dart';

class ArticlePage extends StatefulWidget {
  const ArticlePage({Key? key}) : super(key: key);

  @override
  _ArticlePageState createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage>
    with AutomaticKeepAliveClientMixin {
  late EasyRefreshController _controller;
  List<ArticleItem> _articleList = ArticleList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg = '';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
    _getArticles();
  }

  Future _getArticles({bool push = false}) async {
    List<dynamic> result = await ArticleService.getArticles(page: page);
    ArticleList articleListModel = ArticleList.fromJson(result);
    setState(() {
      //hasMore
      page++;
      if (push) {
        _articleList.addAll(articleListModel.list);
      } else {
        _articleList = articleListModel.list;
      }
    });
  }

  FutureOr _onRefresh() async {
    page = 1;
    await _getArticles();
    _controller.finishRefresh();
    _controller.resetFooter();
  }

  FutureOr _onLoad() async {
    await _getArticles(push: true);
    _controller.finishLoad();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _controller,
      header: ClassicHeader(),
      footer: ClassicFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
        itemCount: _articleList.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            margin: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
            child: ArticleCart(
              articleItem: _articleList[index],
            ),
          );
        },
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
